local skynet   = require "skynet"
local constant = require "constant"

local internal = {}

function internal.get_user_playing_info()
	local value = {}
	local ok, table_list = skynet.call('.table_mgr', 'lua', 'get_table_list')

	if not ok then
		errlog("call .table_mgr error")
		return value
	end

	for table_id, addr in pairs(table_list) do
        local playing_info = skynet.call(addr, 'lua', 'get_user_playing_info')

        if not playing_info then
        	errlog(string.format("playing info is null addr(%s) table_id(%d)", tostring(addr), table_id))
		else        	
    		table.insert(value, playing_info)
	    end
	end

	dbglog(string.format("value(%s)", tostring_r(value)))
	return value
end

local function send_ping_to_user_playing_statistics()
	while true do
		local server_id = tonumber(skynet.getenv "server_id")
		R().user_playing_statistics(1):send('.msg_handler','user_playing_node_ping', server_id)
		--dbglog("send ping to user playing statistics")

		skynet.sleep(constant.SEND_PING_TIME_INTERVAL)
	end
end

function internal.start()
	print('start....')

	--skynet.fork(send_ping_to_user_playing_statistics)
	return true
end

skynet.start(function()
    skynet.dispatch("lua",function(session, source, action, ...)
        dbglog('internal request', action, ...)

        local f = internal[action]
        if f then
            skynet.retpack(f(...))
        else
            errlog("unkown action", action)
        end
    end)
end)